package me.flyray.bsin.server.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * MCP 服务健康检查配置
 */
@Slf4j
@Configuration
@EnableScheduling
public class McpHealthCheckConfig {

    private final AtomicBoolean mcpServiceHealthy = new AtomicBoolean(false);
    private final ToolCallbackProvider tools;

    public McpHealthCheckConfig(@Qualifier("loadbalancedMcpAsyncToolCallbacks") ToolCallbackProvider tools) {
        this.tools = tools;
    }

    /**
     * MCP 服务健康检查指标（简化版本，不依赖 Spring Boot Actuator）
     */
    @Bean
    public McpHealthIndicator mcpHealthIndicator() {
        return new McpHealthIndicator();
    }

    /**
     * MCP 健康检查指标类
     */
    public class McpHealthIndicator {
        public boolean isHealthy() {
            try {
                if (isMcpServiceAvailable()) {
                    mcpServiceHealthy.set(true);
                    return true;
                } else {
                    mcpServiceHealthy.set(false);
                    return false;
                }
            } catch (Exception e) {
                mcpServiceHealthy.set(false);
                return false;
            }
        }
    }

    /**
     * 定期检查 MCP 服务状态
     */
    @Scheduled(fixedRate = 30000) // 每30秒检查一次
    public void checkMcpServiceHealth() {
        try {
            boolean isHealthy = isMcpServiceAvailable();
            if (isHealthy != mcpServiceHealthy.get()) {
                mcpServiceHealthy.set(isHealthy);
                if (isHealthy) {
                    log.info("MCP服务状态恢复，工具集可用");
                } else {
                    log.warn("MCP服务状态异常，工具集不可用");
                }
            }
        } catch (Exception e) {
            log.warn("MCP服务健康检查异常: {}", e.getMessage());
        }
    }

    /**
     * 检查 MCP 服务是否可用
     */
    private boolean isMcpServiceAvailable() {
        try {
            // 尝试获取工具列表来验证 MCP 客户端是否可用
            tools.getToolCallbacks();
            return true;
        } catch (Exception e) {
            log.debug("MCP服务不可用: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 获取 MCP 服务健康状态
     */
    public boolean isMcpServiceHealthy() {
        return mcpServiceHealthy.get();
    }
}
